'use strict';
const Service = require('egg').Service;
const nodemailer = require('nodemailer');
const utilFunc = require('../utils/func');
const _ = require('underscore');
const moment = require('moment');
const mailTransport = nodemailer.createTransport({
  host: 'smtp.qq.com',
  secureConnection: true, // 使用SSL方式（安全方式，防止被窃取信息）
  auth: {
    user: '1143140701@qq.com',
    pass: 'ugmexopwblehbaeg',
  },
});

class LoginKeyService extends Service {
  // 设置key值
  async setLoginKey({ id, skey }) {
    const { app } = this;
    const row = {
      id: 1,
      wx_id: id,
      wx_skey: skey,
    };
    const result = await app.mysql.update('login_key', row);
    if (result.affectedRows === 1) {
      return true;
    }
    return false;
  }
  // 获取到key值
  async getLoginKey() {
    const { app } = this;
    if (app.cache.wx_id !== '') {
      return app.cache;
    }
    const data = await this.refreshLoginKey();
    return data;
  }
  // 刷新key值
  async refreshLoginKey() {
    const { app, ctx } = this;
    const result = await app.mysql.get('login_key', { id: 1 });
    const login_key_obj = JSON.parse(JSON.stringify(result));
    ctx.app.cache.wx_id = login_key_obj.wx_id;
    ctx.app.cache.wx_skey = login_key_obj.wx_skey;
    return login_key_obj;
  }
  // 发送邮件
  // 发送和接收方都已经确定
  async sendEmail(subject = '请注意替换session key', text = '') {
    const { ctx } = this;
    const options = {
      from: '"幽海" 1143140701@qq.com',
      to: '"幽海1" yjsxss10086@163.com,"一二瑞" 1546178144@qq.com',
      subject,
      text,
    };
    if (ctx.app.cache.sendMailTime === 0 || (moment().valueOf() > ctx.app.cache.sendMailTime + 60000)) {
    // 控制10分钟内只调用一次
      mailTransport.sendMail(options, function(err, msg) {
        if (err) {
          ctx.app.cache.sendMailTime === 0;
          return;
        }
        console.log('---发送成功了');
        ctx.app.cache.sendMailTime = moment().valueOf();
        return msg;
      });
      return '大概率成功了';
    }
    return '频率过快';
  }
}
module.exports = LoginKeyService;
